/*
 * Part of knowledge engineering (ke) course work, 2010/11
 */
package se.bth.ke.firstfriend.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.PrePersist;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import se.bth.ke.firstfriend.model.util.Slug;

/**
 *
 * @author nico.rehwaldt
 */
@Entity
@Indexed
public class Topic implements Serializable {

    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Field(index=Index.TOKENIZED)
    private String name;

    @ManyToMany(mappedBy="topics")
    private List<Article> articles;

    private String slug;
    
    public Topic() {
    }

    public Topic(String name) {
        this.name = name;
        this.articles = Collections.emptyList();
    }

    public String getName() {
        return name;
    }

    public Long getId() {
        return id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Topic)) {
            return false;
        }
        Topic other = (Topic) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "se.bth.ke.firstfriend.model.Topic[id=" + id + "]";
    }

    /**
     * @return the articles
     */
    public List<Article> getArticles() {
        if (articles == null) {
            articles = new ArrayList();
        }
        return articles;
    }

    @PrePersist
    private void createSlug() {
        this.slug = Slug.createSlug(name);
    }

    /**
     * @return the slug
     */
    public String getSlug() {
        return slug;
    }
}
